MultiValueMap中put()与addAll()的区别

您所在的位置:网站首页 put set区别 MultiValueMap中put()与addAll()的区别

MultiValueMap中put()与addAll()的区别

2023-11-14 11:57| 来源: 网络整理| 查看: 265

MultiValueMap的特点是一个key键可以对应多个键值,但有一点困扰了我,就是MultiValueMap同时提供了put(key,List)与addAll(key,List)方法,它们有什么区别呢? 首先来看下java文档 put()

/** * Associates the specified value with the specified key in this map * (optional operation). If the map previously contained a mapping for * the key, the old value is replaced by the specified value. (A map * m is said to contain a mapping for a key k if and only * if {@link #containsKey(Object) m.containsKey(k)} would return * true.) * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or * null if there was no mapping for key. * (A null return can also indicate that the map * previously associated null with key, * if the implementation supports null values.) * @throws UnsupportedOperationException if the put operation * is not supported by this map * @throws ClassCastException if the class of the specified key or value * prevents it from being stored in this map * @throws NullPointerException if the specified key or value is null * and this map does not permit null keys or values * @throws IllegalArgumentException if some property of the specified key * or value prevents it from being stored in this map */ V put(K key, V value);

译文: 将指定的值与映射中的指定键关联(可选操作)。如果映射之前包含键的映射,则旧值将被指定的值替换。(当且仅当m. containskey (k)返回true时,表示映射m包含键k的映射。)

addAll()

/** * Add all the values of the given list to the current list of values for the given key. * @param key they key * @param values the values to be added * @since 5.0 */ void addAll(K key, List values);

译文: 将给定列表中的所有值添加到给定键的当前值列表中。

这里已经说明:put()方法是直接替换,addAll()方法是继续添加

测试案例:

@Test public void addMultiValueMap(){ MultiValueMap multiValueMap = new LinkedMultiValueMap(); ArrayList list1 = new ArrayList(); list1.add("aa"); list1.add("bb"); ArrayList list2 = new ArrayList(); list2.add("cc"); ArrayList list3 = new ArrayList(); list3.add("dd"); multiValueMap.put("key1", list1); multiValueMap.put("key1", list2); multiValueMap.put("key1", list3); System.out.println(multiValueMap.get("key1")); multiValueMap.addAll("key2", list1); multiValueMap.addAll("key2", list2); multiValueMap.addAll("key2", list3); System.out.println(multiValueMap.get("key2")); }

输出结果 在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3